package com.yupi.springbootinit.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * exce 相关处理 比如转 csv
 */
@Slf4j
public class ExcelUtils {
    public static String excelToCsv(MultipartFile multipartFile) {
//        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:bi测试数据.xlsx");
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        }
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("读取表格错误",e);
        }
        if (CollUtil.isEmpty(list)) {
            return "";
        }
        //转换为csv
        //虽然线程不安全，但速度快
        StringBuilder stringBuilder = new StringBuilder();
        //1、提取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap) list.get(0);
        //过滤为null的，使用的是动态写法 ,空数据可能也有意义
        List<String> headerList =  headerMap.values().stream().filter(header -> ObjectUtil.isNotEmpty(header)).collect(Collectors.toList());
        stringBuilder.append(StringUtils.join(headerList,",")).append("\n");
        //System.out.println(StringUtils.join(headerList,","));

        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            //静态写法
            List<String> dataList =  dataMap.values().stream().filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList,",")).append("\n");
            //System.out.println(StringUtils.join(dataList,","));
        }


        return stringBuilder.toString();
    }

//    public static void main(String[] args) {
//        excelToCsv(null);
//    }
}
